<?php

namespace App\Console\Commands;

use App\Contract\ContractStatus;
use App\Http\Service\DeviceService;
use App\Jobs\AutoPower;
use App\Jobs\CheckReduce;
use App\Model\Bill;
use App\Model\Contract;
use App\Model\Device;
use App\Model\DeviceBus;
use App\Model\DeviceBuslog;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckBusCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:bus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '设备自动分摊-补扣';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $currentTime = time();
        $oneWeekAgo = $currentTime - (3 * 24 * 60 * 60); // 3天 * 24小时 * 60分钟 * 60秒
        $oneWeekAgoDate = date('Y-m-d H:i:s',$oneWeekAgo);
// 获取一个小时前的时间
        $one_hour_ago = date('Y-m-d H:i:s', strtotime('-1 hour'));
        $list = DeviceBuslog::query()->where('type',2)
            ->whereIn('status',[3,0])
            ->where('updated_at','<',$one_hour_ago)
            ->where('created_at','>=',$oneWeekAgoDate)
            ->limit(10)
            ->orderBy('id','desc')
            ->get();
        $service = app()->make(DeviceService::class);
        foreach ($list as $k=> &$item) {
            $device = Device::query()->where('id',$item->mem_device_id)->first();
            if($device && $device->online_status == 1){
                Log::info('check-bus-log:'.$item->id.'----'.$device->sn);
                $item->mem_du = $device->du;
                $item->status = 0;
                $item->save();
                $service->editDu($device->mac,$item->du);
                dispatch(new CheckReduce($item->id))->delay(120);
            }
        }
    }

}
